package com.zzyl.serve.service.impl;

import java.sql.Wrapper;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.common.utils.uuid.UUID;
import com.zzyl.serve.dto.DeviceDto;
import com.zzyl.serve.vo.DeviceDetailVo;
import com.zzyl.serve.vo.DeviceReportDataVo;
import com.zzyl.serve.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.serve.mapper.DeviceMapper;
import com.zzyl.serve.domain.Device;
import com.zzyl.serve.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;

/**
 * 设备Service业务层处理
 *
 * @author liuyp
 * @date 2025-08-22
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;
    @Resource
    private IoTDAClient client;
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;



    /**
     * 查询设备
     *
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备列表
     *
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return deviceMapper.insert(device);
    }

    /**
     * 修改设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return deviceMapper.updateById(device);
    }

    /**
     * 批量删除设备
     *
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备信息
     *
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return deviceMapper.deleteById(id);
    }
    @Override
    public void syncProductList() {
        //1. 从物联网平台查询所有产品列表
        ListProductsRequest request = new ListProductsRequest();
        ListProductsResponse response = client.listProducts(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口-同步设备列表失败");
        }

        //2. 将产品列表缓存到Redis中
        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST_KEY, JSONUtil.toJsonStr(response.getProducts()));
    }

    @Override
    public List<ProductVo> listAllProduct() {

        //从redis缓存里面获取数据
        String products = (String) redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_KEY);
        if(products == null){
            return null;
        }
        List<ProductVo> list = JSONUtil.toList(products, ProductVo.class);


        return list;
    }

    @Override
    public void register(DeviceDto dto) {

         //1.判断是否已经存在
         //1.1如果设备id已经有了，那么不存
        LambdaQueryWrapper<Device> wrapper = Wrappers.<Device>lambdaQuery()
                .eq(Device::getIotId, dto.getIotId());

        Device device = deviceMapper.selectOne(wrapper);
        if(device != null){
            throw new BaseException("设备已经存在");
        }
         //1.2如果设备名称已经存在，不存

        wrapper =  Wrappers.<Device>lambdaQuery()
                .eq(Device::getDeviceName, dto.getDeviceName());
         device = deviceMapper.selectOne(wrapper);
        if(device != null){
            throw new BaseException("设备已经存在");
        }

         //1.3如果位置类型，物理位置，绑定位置一致，不存
        wrapper =  Wrappers.<Device>lambdaQuery()
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(Device::getPhysicalLocationType, dto.getPhysicalLocationType());
        device = deviceMapper.selectOne(wrapper);
        if(device != null){
             throw new BaseException("设备已经存在");
        }

        //2.将注册的设备保存到华为云
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();

        AuthInfo authInfobody = new AuthInfo();

        body.withAuthInfo(authInfobody);

        body.withProductId(dto.getProductKey());
        body.withDeviceName(dto.getDeviceName());
        body.withNodeId(dto.getNodeId());
        String secret = UUID.randomUUID().toString(true);
        authInfobody.withSecret( secret);
        body.setAuthInfo(authInfobody);
        request.withBody(body);
        AddDeviceResponse response = client.addDevice(request);


        //3.将注册的设备和其他信息封装起来保存到数据库里面
        device = new Device();
        BeanUtils.copyProperties(dto,device);
        device.setSecret(secret);
        device.setIotId(response.getDeviceId());
        save(device);

    }

    @Override
    public DeviceDetailVo getInfo(String iotId) {

        LambdaQueryWrapper<Device> wrapper = Wrappers.<Device>lambdaQuery()
                .eq(Device::getIotId, iotId);

        Device device = deviceMapper.selectOne(wrapper);
        if (device == null) {
            return null;
        }


        //再从华为云IoTDA中查询设备信息
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(request);


        DeviceDetailVo deviceDetailVo = new DeviceDetailVo();
        deviceDetailVo.setDeviceStatus(response.getStatus());
        String activeTime = response.getActiveTime();
        if (activeTime != null) {
            //将activeTime日期字符串值'2025-08-18T13:09:07.104Z'转换成LocalDateTime对象
            LocalDateTime dateTime = LocalDateTime.parse(activeTime, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"));
            //dateTime是0时区的时间，转换成北京东8区
            dateTime = dateTime.atZone(ZoneId.of("UTC")).withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
            deviceDetailVo.setActiveTime(dateTime);
        }
        BeanUtils.copyProperties(device,deviceDetailVo);


        return deviceDetailVo;

    }

    @Override
    public List<DeviceReportDataVo> queryServiceProperties(String iotId) {


        List<DeviceReportDataVo> vos = new ArrayList<>();
        //从华为云IoTDA中查询设备信息
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);


        List<DeviceShadowData> shadow = response.getShadow();
        DeviceShadowData deviceShadowData = shadow.get(0);
        DeviceShadowProperties reported = deviceShadowData.getReported();
        Map<String, Object> properties = (HashMap) reported.getProperties();
        //获取时间evenTime
        String eventTimeStr = shadow.get(0).getReported().getEventTime();
        LocalDateTime reportTime = LocalDateTime.parse(eventTimeStr, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'"));
        LocalDateTime eventTime = reportTime.atZone(ZoneId.of("UTC")).withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
        properties.forEach((key,value)->{
            DeviceReportDataVo vo = new DeviceReportDataVo();
            vo.setFunctionId(key);
            vo.setValue( value);
            vo.setEventTime(eventTime);
            vos.add(vo);
        });
        return vos;
    }

    @Override
    public List<ServiceCapability> queryProductModelProperties(String productId) {
        ShowProductRequest request = new ShowProductRequest();
        request.setProductId(productId);
        ShowProductResponse response = client.showProduct(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口-查询产品信息失败");
        }

        return response.getServiceCapabilities();
    }
}
